package com.jiot.plugin.motan.export;

import java.util.Set;
import com.jfinal.aop.Aop;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.weibo.api.motan.common.MotanConstants;
import com.weibo.api.motan.config.ProtocolConfig;
import com.weibo.api.motan.config.RegistryConfig;
import com.weibo.api.motan.config.ServiceConfig;
import com.weibo.api.motan.util.MotanSwitcherUtil;
import cn.hutool.core.util.ClassUtil;
import rpc_service.MyRPC;

public class ExportKit {
	
	//https://github.com/weibocom/motan/wiki/zh_configuration
	public void startExportRPC(String scanPackage) throws Exception {
		//先获取所有的Export接口实现类
    	Set<Class<?>> sets = ClassUtil.scanPackageByAnnotation(scanPackage, MyRPC.class);
    	for(Class clazz : sets) {
    		//获取这个类关配置组
    		MyRPC rpcExport = (MyRPC) clazz.getAnnotation(MyRPC.class);
    		if(!rpcExport.export()) {
    			continue;
    		}
    		//获取它的接口类
    		Class[] inters = clazz.getInterfaces();
            if (inters == null || inters.length == 0) {
            	throw new Exception(String.format("[%s] 无法找到它继承的接口类", clazz));
            }
            for (Class inter : inters) {
            	
            	ProtocolConfig protocol = new ProtocolConfig();
                protocol.setId(rpcExport.protocolId());
                protocol.setName(rpcExport.protocolName());
                protocol.setDefault(rpcExport.protocolDefault());
            	
                RegistryConfig registry = new RegistryConfig();
                registry.setRegProtocol(rpcExport.registryRegProtocol());//
                registry.setAddress(rpcExport.registryAddress());//"127.0.0.1:2181"
                registry.setCheck(rpcExport.registryCheck()); //是否检查是否注册成功
                registry.setDefault(rpcExport.registryDefault());
                
            	ServiceConfig serviceConfig = new ServiceConfig();
            	serviceConfig.setRegistry(registry);
            	serviceConfig.setProtocol(protocol);
            	serviceConfig.setGroup(rpcExport.Group());
            	serviceConfig.setVersion(rpcExport.Version());
            	serviceConfig.setExport(rpcExport.Export());
            	serviceConfig.setShareChannel(rpcExport.IsShareChannel());
            	serviceConfig.setRequestTimeout(rpcExport.RequestTimeout());
            	
            	serviceExport(inter, Aop.get(clazz), serviceConfig);
            }
            
    	}
	}
	
	public boolean serviceExport(Class interfaceClass, Object Ref, ServiceConfig serviceConfig) {
		
//		synchronized(this) {
			MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, false);

	        serviceConfig.setInterface(interfaceClass);//这个必须是接口
	        serviceConfig.setRef(Ref);//这个必须是接口实现类
	        serviceConfig.export();
	        
	        MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
//		}
        return true;
        
    }
	
	
	
}
